package com.org.zp.ctrl.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.org.base.ctrl.ActivityTaskManager;
import com.org.base.ctrl.BaseActivity;
import com.org.base.ctrl.Constant;
import com.org.base.util.AESEncryptor;
import com.org.base.util.HttpUtils;
import com.org.base.util.URLHelper;
import com.org.zp.R;
import com.org.zp.app.RecApp;
import com.org.zp.ctrl.ComMainActivity;
import com.org.zp.ctrl.UserMainActivity;
import com.org.zp.entity.login.Resume;

/**
 * 登录
 * 
 * @author zhangb
 * 
 */
public class LoginActivity extends BaseActivity {

	private TextView headerTitle; // 顶部条标题
	private Button mButtonBack; // 顶部条返回按钮
	private Button mButtonName; // 顶部条右侧按钮

	private EditText mMailName, mPassWord; // 邮箱名、密码

	private Button mLoginBt; // 登录、注册按钮
	private LinearLayout mReg, mComLogin;
	
	private CheckBox mCheckbox;
	private TextView mForgetPsw;
	
	private SharedPreferences sp;
	
	private RecApp app;

	private ProgressDialog progressDialog;
	private String mClientType = "2";
	private TextView login_com_user_title;
	
	private String mType = "0";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		if (!(ActivityTaskManager.getInstance().containsName("LoginActivity"))) {
			ActivityTaskManager.getInstance().putActivity("LoginActivity", this);
		}
		
		mType = getIntent().getStringExtra("type");//intent.putExtra("type", "0");
		
		app = (RecApp)getApplication();
		
		getComponentId();
	}

	public void getComponentId() {
		
		headerTitle = (TextView) findViewById(R.id.headTitle);
		headerTitle.setText("个人用户登录");
		
		mButtonBack = (Button) findViewById(R.id.back);
		mButtonBack.setText("  返回");
		mButtonBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this,
						UserMainActivity.class);
				startActivity(intent);
				
				ActivityTaskManager.getInstance().removeActivity(
						"LoginActivity");
			}
		});
		
		mButtonName = (Button) findViewById(R.id.top_right_button);
		mButtonName.setVisibility(View.GONE);
		
		login_com_user_title = (TextView)findViewById(R.id.login_com_user_title);
		
		mMailName = (EditText)findViewById(R.id.login_mail);
		mPassWord = (EditText)findViewById(R.id.login_psw);
		
		mLoginBt = (Button)findViewById(R.id.login_bg);
		mLoginBt.setOnClickListener(listener);
		
		mReg = (LinearLayout)findViewById(R.id.logoin_reg);
		mReg.setOnClickListener(listener);
		mComLogin = (LinearLayout)findViewById(R.id.logoin_com_user);
		mComLogin.setOnClickListener(listener);
		
		mCheckbox = (CheckBox)findViewById(R.id.login_check_remenber);
		mCheckbox.setOnClickListener(listener);
		
		mForgetPsw = (TextView)findViewById(R.id.login_forget_psw);
		mForgetPsw.setOnClickListener(listener);
		
		sp = getSharedPreferences(Constant.SHARE_PREFERENCE, Activity.MODE_PRIVATE);
		mMailName.setText(sp.getString(Constant.USERNAME, ""));
		mCheckbox.setChecked(sp.getBoolean(Constant.REMENBER_PASSWORD, false));
		if (mCheckbox.isChecked()) {
			String pwd = "";
			try {
				pwd = AESEncryptor.decrypt(AESEncryptor.KEY, sp.getString(Constant.PASSWORD, ""));
			} catch (Exception e) {
				e.printStackTrace();
			}
			mPassWord.setText(pwd);
		}
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.login_bg:
				if(checkInput()){
					
					progressDialog = ProgressDialog.show(LoginActivity.this,
							"请等待...", "正在登录，请稍后...", true, true);
					
					new getLogin().execute(URLHelper.mPrefix);
				}
				break;
			case R.id.logoin_reg:
				Intent intent = new Intent(LoginActivity.this,
						RegistActivity.class);
				intent.putExtra("type", mType);
				startActivity(intent);
				break;
			case R.id.logoin_com_user:
				if(mClientType.equals("2")){
					mClientType = "1";
					login_com_user_title.setText("个人用户登录入口");
					headerTitle.setText("企业用户登录");
				}else{
					mClientType = "2";
					login_com_user_title.setText("企业用户登录入口");
					headerTitle.setText("个人用户登录");
				}
				break;
			case R.id.login_check_remenber:
				
				break;
			case R.id.login_forget_psw:
				break;
			}

		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(LoginActivity.this,
					UserMainActivity.class);
			startActivity(intent);
			
			ActivityTaskManager.getInstance().removeActivity(
					"LoginActivity");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean checkInput() {
		boolean isNull = true;
		
		if(mMailName.getText().toString().trim().equals("")){
			return false;
		}
		if(mPassWord.getText().toString().trim().equals("")){
			return false;
		}
		
		return isNull;
	}

	
	class getLogin extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
			map.put("act", "login");
			map.put("username", mMailName.getText().toString().trim());
			map.put("password", mPassWord.getText().toString().trim());
			map.put("imei", app.getImei());
			map.put("phone", app.getPhone());
			map.put("imsi", app.getImsi());
			map.put("phoneType", app.getPhoneType());
			
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {
			
			progressDialog.dismiss();

			if (result == null || result.equals("")) {
				// 发送解析数据 消息
				Toast toast = Toast.makeText(LoginActivity.this,
						"失败", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			} else if (result.equals("timeout")) {
				// 发送解析数据 消息
				Toast toast = Toast.makeText(LoginActivity.this,
						"网络超时", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			} else {
				parseJson(result);
			}

		}
	}

	private void parseJson(String str) {
		Log.e("TMG", "splash result = " + str);
		try {
			String succeed = new JSONObject(str).getString("succeed");
			if (succeed.equals("000")) {
				JSONObject json = new JSONObject(str);
				
				app.user.setName(json.getString("username"));
				app.user.setuID(json.getString("uid"));
				app.user.setType(json.getString("utype"));
				
				String data = new JSONObject(str).getString("resumeList");
				JSONArray list = new JSONArray(data);
				
				ArrayList<Resume> resList = new ArrayList<Resume>();

				for (int i = 0; i < list.length(); i++) {
					Resume info = new Resume();
					JSONObject log = list.getJSONObject(i);
					info.setResume_id(log.getString("id"));
					info.setResume_title(log.getString("title"));
					info.setIsdefaultflag(log.getString("audit_cn"));
					info.setResume_addtime(log.getString("addtime"));
					info.setShow_count(log.getString("click"));
					info.setResume_talent_cn(log.getString("talent_cn"));
					resList.add(info);
				}
				
				app.user.setResume(resList);
				
				if(mCheckbox.isChecked()){
					SharedPreferences input = getSharedPreferences(Constant.SHARE_PREFERENCE, Activity.MODE_PRIVATE);
					SharedPreferences.Editor input_editor = input.edit();
					input_editor.putString(Constant.USERNAME, mMailName.getText().toString().trim());
					try {
						Log.d("debug", mPassWord.getText().toString().trim());
						input_editor.putString(Constant.PASSWORD,
								AESEncryptor.encrypt(AESEncryptor.KEY, mPassWord.getText().toString().trim()));

					} catch (Exception e1) {
						e1.printStackTrace();
					}
					input_editor.putBoolean(Constant.REMENBER_PASSWORD, mCheckbox.isChecked());
					input_editor.commit();
				}
				
				if(mType.equals("0")){
					gotoMain();
				}else{
					ActivityTaskManager.getInstance().removeActivity("LoginActivity");
				}
				
			} else if(succeed.equals("001")){
				Toast toast = Toast.makeText(LoginActivity.this,
						"失败", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			} else if(succeed.equals("002")){
				Toast toast = Toast.makeText(LoginActivity.this,
						"用户名不能为空", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			} else if(succeed.equals("003")){
				Toast toast = Toast.makeText(LoginActivity.this,
						"密码不能为空", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			} else if(succeed.equals("004")){
				Toast toast = Toast.makeText(LoginActivity.this,
						"用户名或密码不正确", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void gotoMain(){
		
		if(app.user.getuID().equals("")){
			Intent intent = new Intent(LoginActivity.this,
					UserMainActivity.class);
			startActivity(intent);
		}else if(!app.user.getuID().equals("")){
			if(app.user.getType().equals("2")){
				Intent intent = new Intent(LoginActivity.this,
						UserMainActivity.class);
				startActivity(intent);
			}else{
				Intent intent = new Intent(LoginActivity.this,
						ComMainActivity.class);
				startActivity(intent);
			}
			
		}
		
		
		ActivityTaskManager.getInstance().removeActivity("LoginActivity");
	}

}
